package com.roadjava.javaweb.student.dao.impl;

import com.roadjava.javaweb.student.beans.entity.AdminDO;
import com.roadjava.javaweb.student.dao.AdminDao;
import com.roadjava.javaweb.student.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class AdminDaoImpl implements AdminDao {
    @Override
    public AdminDO validateLogin(String userName) {
        Connection conn = DBUtil.getConn();
        if (conn == null) {
            return null;
        }
        PreparedStatement ps = null;
        ResultSet rs = null;
        StringBuilder sb = new StringBuilder();
        sb.append(" select * from admin where user_name = ? ");
        try {
            ps = conn.prepareStatement(sb.toString());
            ps.setObject(1,userName);
            // 打印最终执行的sql语句
            System.out.println("validateLogin执行的sql:" + ps.toString());
            rs = ps.executeQuery();
            if (rs.next()) {
                long id = rs.getLong("id");
                String pwd = rs.getString("pwd");
                AdminDO adminDO = new AdminDO();
                adminDO.setId(id);
                adminDO.setUserName(userName);
                adminDO.setPwd(pwd);
                return adminDO;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeResultSet(rs);
            DBUtil.closePs(ps);
            DBUtil.closeConn(conn);
        }
        return null;
    }
}
